import { Provide, Inject } from '@midwayjs/core';
import { PrismaService } from './prisma.service';

@Provide()
export class FeedService {
  @Inject()
  prisma: PrismaService;

  async publish(userId: bigint, content: string, imageUrl: string) {
    return this.prisma.dynamic.create({
      data: { userId, content, imageUrl },
    });
  }

  async list(params: { userId?: bigint; page: number; pageSize: number }) {
    const { userId, page, pageSize } = params;
    const where = userId ? { userId } : {};
    const [total, items] = await this.prisma.$transaction([
      this.prisma.dynamic.count({ where }),
      this.prisma.dynamic.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip: (page - 1) * pageSize,
        take: pageSize,
      }),
    ]);
    return { total, items, page, pageSize };
  }

  async incrementRead(id: bigint) {
    return this.prisma.dynamic.update({
      where: { id },
      data: { readCount: { increment: 1 } },
    });
  }
}
